package sdcncsi.ict.counter.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import sdcncsi.ict.counter.CounterService;


@Controller
@RequestMapping("/bin/counter.do")
public class CounterController {
	
	//默认显示处理方式:显示图片
	@RequestMapping
	public void handleDefault(HttpServletRequest request, HttpServletResponse response) {
		handleImage2(request, response);
	}
	
	//隐藏图标处理方法
	@RequestMapping(params = "lb=0")
	public void handleHide(HttpServletRequest request, HttpServletResponse response) {
		CounterService counter = new CounterService();
		//更新计数
		updateCount(counter, request, response);
	}
	
	//显示文字计数
	@RequestMapping(params = "lb=txt")
	public ModelAndView handleText(HttpServletRequest request, HttpServletResponse response) {
		String counterID = request.getParameter("id");
		String appID = request.getParameter("appid");
		if(counterID==null){
			counterID = "1";
		}
		if(appID==null){
			appID = "1";
		}
		CounterService counter = new CounterService();
		//更新计数
		updateCount(counter, request, response);
		int app_id = Integer.parseInt(appID);
		String type = request.getParameter("js");//获得要显示那种计数pv，ip，uv，session
		return new ModelAndView("textView", counter.getCurrentCount(type,app_id,counterID));
	}
	@RequestMapping(params = "lb=1")
	public void handleText2(HttpServletRequest request, HttpServletResponse response) {
		String counterID = request.getParameter("id");
		String appID = request.getParameter("appid");
		if(counterID==null){
			counterID = "1";
		}
		if(appID==null){
			appID = "1";
		}
		CounterService counter = new CounterService();
		//更新计数
		updateCount(counter, request, response);
		int app_id = Integer.parseInt(appID);
		String type = request.getParameter("js");//获得要显示那种计数pv，ip，uv，session
		//获得要显示的数值
		Map data = counter.getCurrentCount(type,app_id,counterID);
		Object messageObj = data.get("count");
		String message = (messageObj==null)?null:messageObj.toString();
		if(message==null){
			message = "Error";
		}
		//输出
		ServletOutputStream responseOutputStream = null;
		try {
			responseOutputStream = response.getOutputStream();
			responseOutputStream.println("document.write('"+message+"')");
			//以下关闭输入流！
			responseOutputStream.flush();
			responseOutputStream.close();
		} catch (IOException e) {
			if(responseOutputStream!=null){
				try {
					responseOutputStream.close();
				} catch (IOException e1) { }
			}
		}
	}
	
	//显示图片计数
	@RequestMapping(params = "lb=img")
	public ModelAndView handleImage(HttpServletRequest request, HttpServletResponse response) {
		String counterID = request.getParameter("id");
		String appID = request.getParameter("appid");
		if(counterID==null){
			counterID = "1";
		}
		if(appID==null){
			appID = "1";
		}
		CounterService counter = new CounterService();
		//更新计数
		updateCount(counter, request, response);
		int app_id = Integer.parseInt(appID);
		String type = request.getParameter("js");//获得要显示那种计数pv，ip，uv，session
		return new ModelAndView("imageView", counter.getCurrentCount(type,app_id,counterID));
	}
	@RequestMapping(params = "lb=2")
	public void handleImage2(HttpServletRequest request, HttpServletResponse response) {
		String counterID = request.getParameter("id");
		String appID = request.getParameter("appid");
		if(counterID==null){
			counterID = "1";
		}
		if(appID==null){
			appID = "1";
		}
		CounterService counter = new CounterService();
		//更新计数
		updateCount(counter, request, response);
		int app_id = Integer.parseInt(appID);
		String type = request.getParameter("js");//获得要显示那种计数pv，ip，uv，session
		//获得要显示的数值
		Map data = counter.getCurrentCount(type,app_id,counterID);
		int count = -1;
		Object messageObj = data.get("count");
		String message = (messageObj==null)?null:messageObj.toString();
		try{
			count = Integer.parseInt(message);
		}catch (NumberFormatException e){
		}
		if(count == -1){//出错了
			message = "Error";
			ServletOutputStream responseOutputStream = null;
			try {
				responseOutputStream = response.getOutputStream();
				responseOutputStream.println("document.write('"+message+"')");
				//以下关闭输入流！
				responseOutputStream.flush();
				responseOutputStream.close();
			} catch (IOException e) {
				if(responseOutputStream!=null){
					try {
						responseOutputStream.close();
					} catch (IOException e1) { }
				}
			}
			return;
		}
		//以图片形式显示
		String shape = request.getParameter("xz");
		outputDigitalImages(count,shape,request,response);
	}
	//javascript输出图片
	private void outputDigitalImages(int count,String shape,HttpServletRequest request,HttpServletResponse response) {
		if(shape==null){
			shape="001";
		}else{
			int shapeInt = 1;
			try{
				shapeInt = Integer.parseInt(shape);
			}catch(NumberFormatException e){}
			if(shapeInt<10){
				shape = "00"+shapeInt;
			}else if(shapeInt<100){
				shape = "0"+shapeInt;
			}else{
				shape = ""+shapeInt;
			}
		}
		String countStr = String.valueOf(count);
		String contextPath = request.getContextPath();
		char[] countChar = countStr.toCharArray();
		StringBuffer strBuf = new StringBuffer(2048);
		for(int i=0;i<countChar.length;i++){
			char digitChar = countChar[i];
			strBuf.append("<img alt=\""+digitChar+"\"" +
					" src=\""+contextPath+"/counter/images/"+shape+"/"+digitChar+".gif\"" +
					" border=\"0\" />");
		}
		
		//输出
		ServletOutputStream responseOutputStream = null;
		try {
			responseOutputStream = response.getOutputStream();
			responseOutputStream.println("document.write('"+strBuf.toString()+"')");
			//以下关闭输入流！
			responseOutputStream.flush();
			responseOutputStream.close();
		} catch (IOException e) {
			if(responseOutputStream!=null){
				try {
					responseOutputStream.close();
				} catch (IOException e1) { }
			}
		}
		return;
		
	}

	//根据HttpServlet对象更新计数器
	private void updateCount(CounterService counter,HttpServletRequest request, HttpServletResponse response){
		//更新计数
		Map<String,String> paramsMap = HttpServletTool.getRequestMap(request);
		counter.updateCount(paramsMap);
		//检测cookie,标识UniqueVisitor，没有则添加
		if(HttpServletTool.getCookie(request, CounterService.COOKIE_NAME)==null){
			int expiry = 30*355*24*60*60;//设置cookie过期时间为30年
			HttpServletTool.addCookie(response, CounterService.COOKIE_NAME,
					paramsMap.get(CounterService.COOKIE_NAME), expiry);
		}
	}
	
	//注册用户
	@RequestMapping(method = RequestMethod.POST, params = "method=register")
	public ModelAndView handleReg(HttpServletRequest request, HttpServletResponse response) {
		Map<String,String> reqMap = HttpServletTool.getRequestMap(request);
		Map rtnMap = CounterService.userRegister(reqMap);
		String viewName = "/index.jsp";
		if((Boolean)rtnMap.get("result")){
			rtnMap.put("countersList", new ArrayList());
		}else{
			viewName = "/register.jsp";
		}
		return new ModelAndView(viewName, "loginRtnMap", rtnMap);
	}
	
	//用户登录
	@RequestMapping(method = RequestMethod.POST, params = "method=login")
	public ModelAndView handleLogin(HttpServletRequest request, HttpServletResponse response) {
		Map<String,String> reqMap = HttpServletTool.getRequestMap(request);
		Map rtnMap = CounterService.userLogin(reqMap);
		if((Boolean)rtnMap.get("result")){
			int user_id = (Integer)rtnMap.get("id");
			List countersList = CounterService.getUserCounters(user_id);
			rtnMap.put("countersList", countersList);
		}
		return new ModelAndView("/index.jsp", "loginRtnMap", rtnMap);
	}
}
